/**
 * 
 */
package sistema.contexto.problemas.dao;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import sistema.contexto.problemas.ProblemaIF;
import sistema.usuario.UsuarioIF;
import util.InvalidFileException;

/**
 * @author Thiago Emmanuel Pereira da Cunha Silva, thiago.manel@gmail.com
 * @since 16/04/2006
 */
public class ProblemaXMLDAO implements ProblemaDAO {

	private String rootDirectory;
	private final String baseFile =  "problemas.xml";//FIXME: TIRA ISSO DAQUI
	private Map<String, ProblemaIF> problemas;
	
	public ProblemaXMLDAO(){
		this("data");
	}
	
	public ProblemaXMLDAO(String rootDirectory){
		setRootDirectory(rootDirectory);
		this.problemas = fromData();
	}
	
	/**
	 * 
	 * @param root
	 */
	public void setRootDirectory (String root){
		this.rootDirectory = root;
	}
	
	/* (non-Javadoc)
	 * @see sistema.contexto.problemas.dao.ProblemaDAO#addProblema(sistema.contexto.problemas.Problema)
	 */
	public void addProblema(ProblemaIF problema) {
		if(getProblema(problema.getId()) != null) {
			throw new IllegalArgumentException("J� existe um problema com o ID especificado");
		}
		this.problemas.put(problema.getId(), problema);
		this.toData(this.problemas);
	}

	/* (non-Javadoc)
	 * @see sistema.contexto.problemas.dao.ProblemaDAO#getProblema(java.lang.String)
	 */
	public ProblemaIF getProblema(String idProblema) {
		this.problemas = this.fromData();
		return this.problemas.get(idProblema);
	}
	
	/* (non-Javadoc)
	 * @see sistema.contexto.problemas.dao.ProblemaDAO#getProblemas()
	 */
	public Collection<ProblemaIF> getProblemas() {
		this.problemas = this.fromData();
		return this.problemas.values();
	}
	
	private  void toData( Map problemas )  {
		try {
			//TODO FIXME refazer, eh aqui mesmo essa verificacao?
			if(!new File(rootDirectory+File.separator+baseFile).exists()) {
				new File(rootDirectory+File.separator+baseFile).createNewFile();
			}
			new ProblemaFileWritter().processFile(rootDirectory+File.separator+baseFile, problemas);
		} catch (Exception e) {
//			//e.printStackTrace(); //decidir quem vai tratar
		}
	}

	private Map fromData( ) {
		try {
			//TODO FIXME refazer, eh aqui mesmo essa verificacao?
			if(!new File(rootDirectory+File.separator+baseFile).exists()) {
				new File(rootDirectory+File.separator+baseFile).createNewFile();
			}
			return (Map) new ProblemaFileReader().processFile(rootDirectory+File.separator+baseFile);
		} catch (Exception e) {}
		return new HashMap<String, ProblemaIF>(); 
	}
	
	public void zerarDados() {
		this.problemas = new HashMap<String,ProblemaIF>();
		this.toData(problemas);
	}

}
